package xin.marcher.module.construction.repository;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Repository;
import xin.marcher.module.common.enums.DelFlagEnum;
import xin.marcher.module.common.enums.ProductResultEnum;
import xin.marcher.module.common.enums.construction.ProductExceptionCode;
import xin.marcher.module.common.enums.price.PriceTypeEnum;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.construction.builder.FullProductData;
import xin.marcher.module.construction.converter.ProductConverter;
import xin.marcher.module.construction.domain.entity.*;
import xin.marcher.module.construction.domain.request.QueryItemListRequest;
import xin.marcher.module.construction.domain.request.QuerySaleSkuRequest;
import xin.marcher.module.construction.domain.request.QuerySkuListRequest;
import xin.marcher.module.construction.mapper.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 商品 资源管理
 */
@Repository
public class ProductInfoRepository {

    @Resource
    private ProductConverter productConverter;
    @Resource
    private ItemInfoMapper itemInfoMapper;

    @Resource
    private ItemShelfLifeMapper itemShelfLifeMapper;

    @Resource
    private ItemVideoImgMapper itemVideoImgMapper;

    @Resource
    private SkuInfoMapper skuInfoMapper;

    @Resource
    private SkuSellerRelationMapper skuSellerRelationMapper;

    @Resource
    private SkuPriceSellerRelationMapper skuPriceSellerRelationMapper;

    @Resource
    private SkuPriceUpdateRecordMapper skuPriceUpdateRecordMapper;

    @Resource
    private SkuBarCodeRelationMapper skuBarCodeRelationMapper;

    @Resource
    private CspuSkuRelationMapper cspuSkuRelationMapper;

    @Resource
    private QualityControlMapper qualityControlMapper;

    @Resource
    private AttributeExtendMapper attributeExtendMapper;

    @Resource
    private ProductStatusStrategyMapper productStatusStrategyMapper;

//    @Autowired
//    private SellerRemote sellerRemote;

    /**
     * 保存商品的明细信息
     *
     * @param fullProductData
     */
    public void saveItemInfo(FullProductData fullProductData) {
        // 保存商品Item的信息
        saveItemInfo(fullProductData.getItemInfoDO());
        //保存商品保质期信息
        saveItemShelfLife(fullProductData.getItemShelfLifeDO());
        //批量保存商品图片视频信息
        saveBatchVideoImg(fullProductData.getItemVideoImgDOList());
        //批量保存商品sku信息
        saveBatchSkuInfo(fullProductData.getSkuInfoDOList());
        //批量保存69码信息
        saveBatchSkuBarCodeRelation(fullProductData.getSkuBarCodeRelationDOList());
        //批量保存CSPU与SKU关系
        saveBatchCspuSkuRelation(fullProductData.getCspuSkuRelationDOList());
        //批量保存品控信息
        saveBatchQualityControl(fullProductData.getQualityControlDOList());
        //保存 ITEM或SKU扩展属性
        saveAttributeExtend(fullProductData.getAttributeExtendDO());
    }

    /**
     * 修改商品的明细信息
     *
     * @param fullProductData
     */
    public void updateItemInfo(FullProductData fullProductData) {
        // 更新商品item信息
        updateItemInfo(fullProductData.getItemInfoDO());
        // 更新商品保质期信息
        updateItemShelfLife(fullProductData.getItemShelfLifeDO());
        // 更新商品扩展信息
        updateAttributeExtend(fullProductData.getAttributeExtendDO());
        // 更新商品的视频图片信息
        batchUpdateVideoImg(fullProductData.getItemVideoImgDOList());
        // 批量更新商品sku信息
        batchUpdateSkuInfo(fullProductData.getSkuInfoDOList());
        // 批量更新商品的69规格
        batchUpdateSkuBarCodeRelation(fullProductData.getSkuBarCodeRelationDOList());
        // 批量更新 CSPU与SKU关系
        batchUpdateCspuSkuRelation(fullProductData.getCspuSkuRelationDOList());
        // 批量更新品控信息
        batchUpdateQualityControl(fullProductData.getQualityControlDOList());
    }

    /**
     * 批量更新品控信息
     *
     * @param qualityControlDOList
     */
    private void batchUpdateQualityControl(List<QualityControlDO> qualityControlDOList) {
        qualityControlDOList.stream().forEach(e -> {
            qualityControlMapper.updateById(e);
        });
    }

    /**
     * 批量更新 CSPU与SKU关系
     *
     * @param cspuSkuRelationDOList
     */
    private void batchUpdateCspuSkuRelation(List<CspuSkuRelationDO> cspuSkuRelationDOList) {
        cspuSkuRelationDOList.stream().forEach(e -> {
            cspuSkuRelationMapper.updateById(e);
        });
    }

    /**
     * 批量更新商品的69规格
     *
     * @param skuBarCodeRelationDOList
     */
    private void batchUpdateSkuBarCodeRelation(List<SkuBarCodeRelationDO> skuBarCodeRelationDOList) {
        skuBarCodeRelationDOList.stream().forEach(e -> {
            skuBarCodeRelationMapper.updateById(e);
        });
    }

    /**
     * 批量更新商品的sku信息
     *
     * @param skuInfoDOList
     */
    private void batchUpdateSkuInfo(List<SkuInfoDO> skuInfoDOList) {
        skuInfoDOList.stream().forEach(e -> {
            skuInfoMapper.updateById(e);
        });
    }

    /**
     * 批量修改商品的视频图片信息
     *
     * @param itemVideoImgDOList
     */
    private void batchUpdateVideoImg(List<ItemVideoImgDO> itemVideoImgDOList) {
        itemVideoImgDOList.stream().forEach(e -> {
            itemVideoImgMapper.updateById(e);
        });
    }

    /**
     * 更新商品的扩展信息
     *
     * @param attributeExtendDO
     */
    private void updateAttributeExtend(AttributeExtendDO attributeExtendDO) {
        int count = attributeExtendMapper.updateById(attributeExtendDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 更新保质期信息
     *
     * @param itemShelfLifeDO
     */
    private void updateItemShelfLife(ItemShelfLifeDO itemShelfLifeDO) {
        int count = itemShelfLifeMapper.updateById(itemShelfLifeDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 更新商品item信息
     *
     * @param itemInfoDO
     */
    private void updateItemInfo(ItemInfoDO itemInfoDO) {
        int count = itemInfoMapper.updateById(itemInfoDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 新增卖家定价
     *
     * @param skuPriceSellerRelationDO
     */
    public void saveRecord(SkuPriceSellerRelationDO skuPriceSellerRelationDO) {
        skuPriceSellerRelationDO.initCommon();
        skuPriceSellerRelationMapper.insert(skuPriceSellerRelationDO);
    }

    /**
     * 保存商品sku变更信息
     *
     * @param skuInfoDO
     */
    public void saveRecord(SkuInfoDO skuInfoDO, SkuPriceSellerRelationDO skuPriceSellerRelationDO) {
        // 获取变更前的商品信息
        SkuInfoDO oldSkuInfoDO = getSkuInfoBySkuId(skuInfoDO.getSkuId());
        // 记录商品改价变更
        saveRecord(skuInfoDO, oldSkuInfoDO, skuPriceSellerRelationDO);

        // 正式更新商品价格
        updateSkuPrice(skuPriceSellerRelationDO);
    }

    /**
     * 正式更新商品价格
     *
     * @param entity
     */
    private void updateSkuPrice(SkuPriceSellerRelationDO entity) {
        LambdaUpdateWrapper<SkuPriceSellerRelationDO> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(Objects.nonNull(entity.getSkuId()), SkuPriceSellerRelationDO::getSkuId, entity.getSkuId());
        updateWrapper.eq(Objects.nonNull(entity.getSellerId()), SkuPriceSellerRelationDO::getSellerId, entity.getSellerId());
        updateWrapper.eq(Objects.nonNull(entity.getPriceType()), SkuPriceSellerRelationDO::getPriceType, entity.getPriceType());
        // 商城价或会员价
        updateWrapper.set(Objects.nonNull(entity.getPrice()), SkuPriceSellerRelationDO::getPrice, entity.getPrice());

        int count = skuPriceSellerRelationMapper.update(null, updateWrapper);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 保存 ITEM或SKU扩展属性
     *
     * @param attributeExtendDO
     */
    private void saveAttributeExtend(AttributeExtendDO attributeExtendDO) {
        int count = attributeExtendMapper.insert(attributeExtendDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 批量保存品控信息
     *
     * @param qualityControlDOList
     */
    private void saveBatchQualityControl(List<QualityControlDO> qualityControlDOList) {
        int count = qualityControlMapper.saveBatch(qualityControlDOList);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 批量保存CSPU与SKU关系
     *
     * @param cspuSkuRelationDOList
     */
    private void saveBatchCspuSkuRelation(List<CspuSkuRelationDO> cspuSkuRelationDOList) {
        int count = cspuSkuRelationMapper.saveBatch(cspuSkuRelationDOList);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 批量保存69码信息
     *
     * @param skuBarCodeRelationDOList
     */
    private void saveBatchSkuBarCodeRelation(List<SkuBarCodeRelationDO> skuBarCodeRelationDOList) {
        int count = skuBarCodeRelationMapper.saveBatch(skuBarCodeRelationDOList);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 批量保存商品sku信息
     *
     * @param skuInfoDOList
     */
    private void saveBatchSkuInfo(List<SkuInfoDO> skuInfoDOList) {
        int count = skuInfoMapper.saveBatch(skuInfoDOList);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 批量保存商品图片视频信息
     *
     * @param itemVideoImgDOList
     */
    private void saveBatchVideoImg(List<ItemVideoImgDO> itemVideoImgDOList) {
        int count = itemVideoImgMapper.saveBatch(itemVideoImgDOList);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 保存商品保质期信息
     *
     * @param itemShelfLifeDO
     */
    private void saveItemShelfLife(ItemShelfLifeDO itemShelfLifeDO) {
        int count = itemShelfLifeMapper.insert(itemShelfLifeDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 保存商品Item的信息
     *
     * @param itemInfoDO
     */
    private void saveItemInfo(ItemInfoDO itemInfoDO) {
        int count = itemInfoMapper.insert(itemInfoDO);
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    /**
     * 记录商品改价变更
     *
     * @param skuInfoDO
     * @param oldSkuInfoDO
     */
    private void saveRecord(SkuInfoDO skuInfoDO, SkuInfoDO oldSkuInfoDO, SkuPriceSellerRelationDO skuPriceSellerRelationDO) {
        SkuPriceUpdateRecordDO skuPriceUpdateRecordDO = productConverter.converterDO(skuInfoDO);

        if (!Objects.equals(oldSkuInfoDO.getBasePrice(), skuInfoDO.getBasePrice())) {
            // 商城价
            skuPriceUpdateRecordDO.setPriceType(PriceTypeEnum.BASE_PRICE.getCode());
            skuPriceUpdateRecordDO.setPrice(skuInfoDO.getBasePrice());
            skuPriceUpdateRecordDO.setPriceOld(oldSkuInfoDO.getBasePrice());
        } else {
            // 会员价
            skuPriceUpdateRecordDO.setPriceType(PriceTypeEnum.VIP_PRICE.getCode());
            skuPriceUpdateRecordDO.setPrice(skuInfoDO.getVipPrice());
            skuPriceUpdateRecordDO.setPriceOld(oldSkuInfoDO.getVipPrice());
        }
        skuPriceUpdateRecordDO.setSkuId(skuPriceSellerRelationDO.getSkuId());
        skuPriceUpdateRecordDO.setSellerType(skuPriceSellerRelationDO.getSellerType());
        skuPriceUpdateRecordDO.setSellerId(skuPriceSellerRelationDO.getSellerId());
        skuPriceUpdateRecordDO.setPriceType(skuPriceSellerRelationDO.getPriceType());
        skuPriceUpdateRecordDO.setChangeReason(skuPriceSellerRelationDO.getChangeReason());
        skuPriceUpdateRecordDO.setSuggestedMallPrice(skuPriceSellerRelationDO.getSuggestedMallPrice());
        skuPriceUpdateRecordDO.setDelFlag(DelFlagEnum.EFFECTIVE.getCode());
        skuPriceUpdateRecordDO.setCreateUserOld(oldSkuInfoDO.getCreateUser());
        skuPriceUpdateRecordDO.setCreateTimeOld(oldSkuInfoDO.getCreateTime());
        this.skuPriceUpdateRecordMapper.insert(skuPriceUpdateRecordDO);
    }

    /**
     * 根据SkuId 查询商品SKU信息
     *
     * @param skuId
     * @return
     */
    public SkuInfoDO getSkuInfoBySkuId(String skuId) {
        LambdaQueryWrapper<SkuInfoDO> queryWrapper = Wrappers.lambdaQuery();
        return skuInfoMapper.selectOne(queryWrapper.eq(SkuInfoDO::getSkuId, skuId));
    }

    /**
     * 判断是否写入成功，返回写入条数小于等于0认为新增失败
     *
     * @param count
     */
    private void checkDBOperation(Integer count) {
        if (count <= 0) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_SQL);
        }
    }

    public ItemInfoDO selectByItemId(String itemId) {
        return itemInfoMapper.selectByItemId(itemId);
    }

    /**
     * 查询可售列表
     *
     * @param querySaleSkuRequest
     * @return
     */
    public List<SkuSellerRelationDO> querySkuSellerList(QuerySaleSkuRequest querySaleSkuRequest) {
        // 查询可售的sku
        LambdaQueryWrapper<SkuSellerRelationDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SkuSellerRelationDO::getSellerGroupId, querySaleSkuRequest.getSellerId());
        if (!CollectionUtils.isEmpty(querySaleSkuRequest.getSkuIdSet())) {
            queryWrapper.in(SkuSellerRelationDO::getSkuId, querySaleSkuRequest.getSkuIdSet());
        }

        return skuSellerRelationMapper.selectList(queryWrapper);
    }

    /**
     * 根据itemId查询item信息
     *
     * @param itemId
     * @return
     */
    public ItemInfoDO getItemByItemId(String itemId) {
        ItemInfoDO itemInfoDO = itemInfoMapper.selectByItemId(itemId);
        if (Objects.isNull(itemInfoDO)) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_DETAIL_NULL);
        }
        return itemInfoDO;
    }


    /**
     * 获取对应的修改状态流程策略映射码
     *
     * @param startStatus
     * @param endStatus
     * @param businessCode
     * @return
     */
    public String getProductStatusStrategy(Integer startStatus, Integer endStatus, String businessCode) {
        LambdaQueryWrapper<ProductStatusStrategyDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ProductStatusStrategyDO::getStartStatus, startStatus);
        queryWrapper.eq(ProductStatusStrategyDO::getEndStatus, endStatus);
        queryWrapper.eq(ProductStatusStrategyDO::getBusinessCode, businessCode);

        ProductStatusStrategyDO productStatusStrategy = productStatusStrategyMapper.selectOne(queryWrapper);
        if (Objects.isNull(productStatusStrategy)) {
            throw new BaseBizException(ProductExceptionCode.PRODUCT_STRATEGY_NULL);
        }
        return productStatusStrategy.getStrategyCode();
    }

    /**
     * 根据itemId查询item信息
     *
     * @param queryItemListRequest
     * @return
     */
    public List<ItemDetailDO> listItemByItemIds(QueryItemListRequest queryItemListRequest) {
        Set<String> itemIdSet = queryItemListRequest.getItemIdSet();
        List<Integer> customResult = queryItemListRequest.getCustomResult();
        //构建商品信息枚举值集合
        List<ProductResultEnum> customEnumResult = buildProductResultEnumList(customResult);

        List<ItemDetailDO> itemDetailDOS = itemInfoMapper.selectItemDetailList(itemIdSet, customEnumResult);
        if (customResult.contains(ProductResultEnum.SALE.getCode())) {
            // 填充itemDetailDTOS的销售信息
            setItemSaleResult(itemDetailDOS);
        }
        if (customResult.contains(ProductResultEnum.POPULARIZE.getCode())) {
            // 填充itemDetailDTOS的推广信息
            setItemPopularizeResult(itemDetailDOS);
        }
        return itemDetailDOS;
    }

    /**
     * 构建商品信息枚举值集合
     *
     * @param customResult
     * @return
     */
    private List<ProductResultEnum> buildProductResultEnumList(List<Integer> customResult) {
        List<ProductResultEnum> customEnumResult = new ArrayList<>();
        for (Integer resultType : customResult) {
            customEnumResult.add(ProductResultEnum.getByCode(resultType));
        }
        return customEnumResult;
    }


    /**
     * 设置item的销售信息结果
     *
     * @param itemDetailDOS
     */
    private void setItemSaleResult(List<ItemDetailDO> itemDetailDOS) {
        for (ItemDetailDO itemDetailDO : itemDetailDOS) {
            itemDetailDO.setItemSaleDO(getItemSaleByItemId(itemDetailDO.getItemInfoDO().getItemId()));
        }
    }

    /**
     * 设置item的推广信息结果
     *
     * @param itemDetailDOS
     */
    private void setItemPopularizeResult(List<ItemDetailDO> itemDetailDOS) {
        for (ItemDetailDO itemDetailDO : itemDetailDOS) {
            itemDetailDO.setItemPopularizeDO(getItemPopularizeByItemId(itemDetailDO.getItemInfoDO().getItemId()));
        }
    }


    private ItemSaleDO getItemSaleByItemId(String itemId) {
        return new ItemSaleDO(itemInfoMapper.selectItemSaleByItemId(itemId));
    }

    private ItemPopularizeDO getItemPopularizeByItemId(String itemId) {
        return itemInfoMapper.selectItemPopularizeByItemId(itemId);
    }

    public List<SkuInfoDO> listSkuByItemId(String itemId) {
        LambdaQueryWrapper<SkuInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SkuInfoDO::getItemId, itemId);
        return skuInfoMapper.selectList(queryWrapper);
    }

    public List<SkuDetailDO> listSkuDetailByLike(QuerySkuListRequest querySkuListRequest, List<Integer> customResult) {
        return skuInfoMapper.selectDetailByLike(querySkuListRequest, customResult);
    }

    public List<SkuDetailDO> listSkuDetailBySkuId(Set<String> skuIdSet, List<Integer> customResult) {
        return skuInfoMapper.selectDetailBySkuId(skuIdSet, customResult);
    }

    public List<SkuDetailDO> listSkus(QuerySkuListRequest querySkuListRequest) {
        Set<String> skuIdSet = querySkuListRequest.getSkuIdSet();
        List<Integer> customResult = querySkuListRequest.getCustomResult();

        List<SkuDetailDO> skuDetailList;
        if (CollectionUtils.isEmpty(skuIdSet)) {
            skuDetailList = listSkuDetailByLike(querySkuListRequest, customResult);
        } else {
            skuDetailList = listSkuDetailBySkuId(skuIdSet, customResult);
        }

        // sku 是否 需要查询销售信息
//        if (customResult.contains(ProductResultEnum.SALE.getCode())) {
//            // 填充skuDetailDTOS的销售信息
//            setSkuSaleResult(skuDetailList, ProductResultEnum.SALE);
//        }

        // 需要查询推广信息
        if (customResult.contains(ProductResultEnum.POPULARIZE.getCode())) {
            // 填充skuDetailDTOS的推广信息
            setSkuPopularizeResult(skuDetailList);
        }
        return skuDetailList;
    }

    private void setSkuPopularizeResult(List<SkuDetailDO> skuDetailList) {
        for (SkuDetailDO skuDetailDO : skuDetailList) {
            skuDetailDO.setItemPopularizeDO(getItemPopularizeByItemId(skuDetailDO.getSkuInfoDO().getItemId()));
        }
    }
}
